package com.bdqn.qnnews.aliyungreen.config;

import com.aliyun.green20220302.Client;
import com.aliyun.teaopenapi.models.Config;
import com.bdqn.qnnews.aliyungreen.utils.AliYunGreenUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author xlzhang
 * @date 2024/1/2 13:43
 */
@Configuration
@ConditionalOnClass({Config.class,Client.class})
@EnableConfigurationProperties(AliYunGreenProperties.class)
public class AliYunGreenAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(Client.class)
    public Client aliYunGreenClient(AliYunGreenProperties prop){
        Config config = new Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(prop.getAccessKeyId())
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(prop.getAccessKeySecret())
                // 访问的域名
                .setEndpoint(prop.getEndpoint())
                //连接时超时时间，单位毫秒（ms）。
                .setReadTimeout(6000)
                //读取时超时时间，单位毫秒（ms）。
                .setConnectTimeout(3000);

        // 注意，此处实例化的client请尽可能重复使用，避免重复建立连接，提升检测性能
        try {
            return new Client(config);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Bean
    @ConditionalOnMissingBean(AliYunGreenUtil.class)
    public AliYunGreenUtil aliYunGreenUtil(Client client, AliYunGreenProperties prop){
        return new AliYunGreenUtil(client,prop);
    }

}
